# -*- encoding: utf-8 -*-

# ============ User Configurations Goes Here ===============
# Put your application name here
# example: URL = http://helloGAE.appspot.com
URL = 'http://<your application>.appspot.com'

# Put the default directory to save files here
# example: OUTPUT_DIR = '/sdcard/sync'
OUTPUT_DIR = ''

# Put the token here. The token is intended for identification
# Must be consistent with the one in your server configuration
# eg: TOKEN = 'HELLWORLD'
TOKEN = ''
# ============ User Configurations Ends Here ===============

import json
import urllib
import urllib2
import os

print "Starting Download"

if not os.path.exists(OUTPUT_DIR):
    os.mkdir(OUTPUT_DIR)

print "Opening Web Page: %s" % (URL + '/list/' + TOKEN)
web = urllib.urlopen(URL + '/list/' + TOKEN )

content = web.read()
print "Loading JSON: %s" % content
book_list = json.loads(content)

print "Parsing Book List..."

for book in book_list:
    print book['name'], book['url']

    output_dir = OUTPUT_DIR

    if book['odir']:
        output_dir = book['odir']
        
    print "Write to: %s" % (output_dir + "/" + book['name']) 

    if os.path.exists(output_dir + "/" + book['name']):
        print "Book exists: %s" % book['name']
        print "Ignore"
    else:
        print "Write to file: %s" % book['name']
        fi = urllib2.urlopen(URL + '/' + urllib.quote(book['url']) + '/' + TOKEN)
        output = open(output_dir + '/' + book['name'],'wb')
        output.write(fi.read())
        output.close()    
    
